package spring.springbucks.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import spring.springbucks.service.CoffeeItemService;
import spring.springentity.entity.table.CoffeeEntity;
import spring.springentity.repository.CoffeeRepository;

import java.util.Optional;

@Slf4j
@Service
public class CoffeeItemServiceImpl implements CoffeeItemService {

  private static final String CACHE = "springbucks-coffee";

  @Autowired
  private CoffeeRepository coffeeRepository;

  //@Autowired
  //private RedisTemplate<String, CoffeeEntity> redisTemplate;

  @Override
  @Cacheable(cacheNames = "springbucks-coffee", key = "#name")
  public Optional<CoffeeEntity> findOneCoffee(String name) {
    //HashOperations<String, String, CoffeeEntity> hashOperations = redisTemplate.opsForHash();
    //if (redisTemplate.hasKey(CACHE) && hashOperations.hasKey(CACHE, name)) {
    //  log.info("Get coffee {} from Redis.", name);
    //  return Optional.of(hashOperations.get(CACHE, name));
    //}
    CoffeeEntity coffee = coffeeRepository.getOne(new QueryWrapper<CoffeeEntity>().eq("NAME", name.toUpperCase()).eq("SYS_IS_DELETED", 0));
    log.info("Coffee Found: {}", coffee);

    //if (coffee != null) {
    //  log.info("Put coffee {} to Redis.", name);
    //  hashOperations.put(CACHE, name, coffee);
    //  redisTemplate.expire(CACHE, 1, TimeUnit.MINUTES);
    //}
    return Optional.ofNullable(coffee);
  }
}
